<template>
  <div class="buys">
    <div class="buys-title">买票</div>
    <div class="buys-item">
      <el-form
        ref="formRef"
        :inline="true"
        :model="buys"
        class="demo-form-inline"
        label-position="top"
        size="default"
        :rules="buysRules"
        @keyup.enter="handleBuysEnter"
        @click.stop
      >
        <!-- 表单字段 -->
        <el-form-item label="承兑人信息" prop="acceptor">
          <el-input ref="firstInput" v-model="buys.acceptor" style="width: 120px" />
        </el-form-item>
        <el-form-item label="票面金额(万元)" prop="billAmount">
          <el-input
            v-model="buys.billAmount"
            placeholder=""
            style="width: 120px"
            @input="handleInput('billAmount')"
          />
        </el-form-item>
        <el-form-item label="点数" prop="points">
          <el-input
            v-model="buys.points"
            placeholder=""
            style="width: 80px"
            @input="handleInput('points')"
          />
        </el-form-item>
        <el-form-item label="张数" prop="open">
          <el-select v-model="buys.open" placeholder="" style="width: 80px">
            <el-option v-for="number in 10" :key="number" :label="number" :value="number" />
          </el-select>
        </el-form-item>
        <el-form-item style="display: flex; align-items: flex-end">
          <el-button v-if="!isEditBoolenbuy" type="primary" @click="onSubmit(formRef, 'buysList')"
            >添加</el-button
          >
          <el-button v-else type="primary" @click="doEdit('buys')">修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import type { FormInstance, FormRules } from 'element-plus'
import { inputFormat, dealWith, dealWithEdit } from './utils/from'
import { tableDataStoreHook } from '@store/dataStore' // 引入数据store
import { useScrollStoreHook } from '@store/scrollStore' // 引入滚动store

// 获取store实例
const tableDataStore = tableDataStoreHook()
const scrollStore = useScrollStoreHook()

// 使用storeToRefs确保响应式
const { buys, isEditBoolenbuy } = storeToRefs(tableDataStore)

interface RuleForm {
  acceptor: string
  billAmount: string
  points: string
  open: string
}

const buysRules = reactive<FormRules<RuleForm>>({
  acceptor: [{ required: true, message: '请输入承兑人信息', trigger: 'blur' }],
  billAmount: [{ required: true, message: '请输入票面金额（万元）', trigger: 'blur' }],
  points: [{ required: true, message: '请输入点数', trigger: 'blur' }],
  open: [
    {
      required: true,
      message: '请选择张数',
      trigger: 'change'
    }
  ]
})

interface BuysItem {
  serialNumber: number
  matter: string
  acceptor: string
  billAmount: string
  points: string
  open: number
  rebate: string
  interestDeduction: string
  checked?: boolean
}

const formRef = ref<FormInstance>()
const firstInput = ref<HTMLInputElement>()
const item = ref<BuysItem>({
  serialNumber: 1,
  matter: '',
  acceptor: '',
  billAmount: '',
  points: '',
  open: 1,
  rebate: '',
  interestDeduction: ''
})

const handleInput = (field: string) => {
  console.log(buys.value[field])
  buys.value[field] = inputFormat(field, buys.value)
}

const handleBuysEnter = () => {
  if (isEditBoolenbuy.value) {
    doEdit('buys')
  } else {
    onSubmit(formRef.value, 'buysList')
  }
}

// ========== 关键修改：添加触发滚动函数 ==========
// 公共提交方法
const onSubmit = async (formEl: FormInstance | undefined, type: string) => {
  if (!formEl) return

  try {
    // 1. 先进行表单验证
    await formEl.validate()

    // 2. 处理业务逻辑
    const result = await dealWith(type, buys.value)

    if (result) {
      // 3. 提交数据到store
      tableDataStore.doSubmit(result, 'buysList')

      // 4. 重置表单
      formEl.resetFields()
      firstInput.value?.focus()

      // 5. 触发滚动到最新行（在nextTick中确保DOM已更新）
      nextTick(() => {
        scrollStore.triggerScroll('buysList')
      })
    }
  } catch (error) {
    // 验证失败处理
    console.error('表单验证失败:', error)
  }
}

// 公共修改方法
const doEdit = async (type: string) => {
  if (!formRef.value) return

  try {
    // 1. 先进行表单验证
    await formRef.value.validate()

    // 2. 处理业务逻辑
    const result = await dealWithEdit(type, buys.value, item.value)

    if (result) {
      // 3. 更新数据到store
      tableDataStore.doUpdate(result, 'buysList')

      // 4. 重置表单
      formRef.value.resetFields()
      firstInput.value?.focus()

      // 5. 触发滚动（如果需要）
      nextTick(() => {
        scrollStore.triggerScroll('buysList')
      })
    }
  } catch (error) {
    // 验证失败处理
    console.error('表单验证失败:', error)
  }
}
// ========== 结束关键修改 ==========
</script>

<style lang="scss" scoped>
.buys {
  width: 100%;
  height: 100%;
  padding: 12px;
  // background: #f8f9fa;
  // border-radius: 8px;
  // border: 1px solid #ccc;

  .buys-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 10px;
  }

  .buys-item {
    display: flex;
    width: 100%;
    height: 100%;
  }
}
</style>
